package com.bestcem.xm.survey.grpc.client;

import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.push.grpc.v1.services.GetUserInfoBySessionIdRequest;
import com.bestcem.xm.push.grpc.v1.services.GetUserInfoBySessionIdResponse;
import com.bestcem.xm.push.grpc.v1.services.WechatOfficialAccountServiceGrpc;
import com.bestcem.xm.survey.convert.grpc.SurveyGrpcConvertMapper;
import com.bestcem.xm.survey.util.SnakeFastJsonUtil;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 这里应该要换成直接对接微信后台，而不是依赖push服务
 *
 * @ClassName: PushGrpcClient
 * @Author: chenglong.yue
 * @Date: 2022/10/13 16:56
 */
@Slf4j
@Component
public class PushGrpcClient {
    @GrpcClient(GrpcClientNames.DS_PUSH)
    private WechatOfficialAccountServiceGrpc.WechatOfficialAccountServiceBlockingStub stub;

    private final SurveyGrpcConvertMapper grpcConvertMapper;

    public PushGrpcClient(SurveyGrpcConvertMapper grpcConvertMapper) {
        this.grpcConvertMapper = grpcConvertMapper;
    }

    public JSONObject getUserInfoBySessionId(String sessionId) {
        GetUserInfoBySessionIdRequest.Builder builder = GetUserInfoBySessionIdRequest.newBuilder();
        builder.setSessionId(sessionId);
        try {
            GetUserInfoBySessionIdResponse response = stub.getUserInfoBySessionId(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] getUserInfoBySessionId, sessionId = {} Error; ErrorMsg: {}", sessionId, response);
                return new JSONObject();
            }

            //这次骚一点，不用@JSONField
            JSONObject ret = new JSONObject();
            ret.put("info", SnakeFastJsonUtil.toSnakeMap(grpcConvertMapper.toPushUserInfoDto(response.getInfo())));
            ret.put("scope", response.getScope());
            return ret;
        } catch (Exception e) {
            log.error("[survey] getUserInfoBySessionId, sessionId = {} Error; ErrorMsg: {}", sessionId, e.getMessage());
            return new JSONObject();
        }
    }
}
